<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import { Message, PaginationProps } from "@arco-design/web-vue";
import type {
  ListRacetrackType,
  OtherChildrenListType,
} from "@/types/commonType.ts";
import {
  back,
  downPdf,
  getRegistrationList,
  resetStep,
} from "@/services/newsApi.ts";
import {
  getDictByParentCode,
  listNormalRacetrack,
  listRacetrack,
} from "@/services/commonApi.ts";
import { downloadFile, getUser } from "@/utils";
import { tableBorder } from "@/utils/border/table-border.ts";
import RegistrationOrgin from "@/pages/news/registrationCenter/registrationOrgin.vue";
import RegistrationForm from "@/pages/news/registrationCenter/registrationForm.vue";
import useModal from "@/hooks/useModal.ts";
import AchieveModal from "@/pages/review/achievement/AchieveModal.vue";

const colProps = {
  xs: 24,
  sm: 24,
  md: 12,
  lg: 8,
  xl: 8,
  xxl: 8,
};

const achieveRef = ref<{
  init: (data: any) => void;
}>();

const helpform = ref<{
  show: () => void;
}>();

const orginform = ref<{
  show: () => void;
}>();

const { ModalShow, ModalHide } = useModal();

const data = ref([]);

const registUid = ref("");

const racetrackList = ref<
  {
    id: string;
    itemText: string;
  }[]
>([]);

const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  showTotal: true,
  pageSize: 10,
});

const formSearch = reactive({
  current: 1,
  size: 10,
  phone: "",
  projectType: "0",
  projectSource: "",
  channel: "",
  dataDirection: "",
  step: 3,
  projectName: "",
});

const options = reactive<{
  参赛项目来源: OtherChildrenListType[];
  赛道: ListRacetrackType[];
  企业赛道: ListRacetrackType[];
  loading: boolean;
  export: boolean;
}>({
  参赛项目来源: [],
  赛道: [],
  企业赛道: [],
  loading: false,
  export: false,
});

function queryData() {
  // data.value = [];
  options.loading = true;
  getRegistrationList(formSearch)
    .then((res) => {
      if (res.code === 200) {
        data.value = res.data.records;
        pagination.total = res.data.total;
        pagination.current = res.data.current;
        pagination.pageSize = res.data.size;
      } else {
        data.value = [];
        Message.error(res.msg);
      }
    })
    .finally(() => {
      options.loading = false;
    });
}

const handlePageChange = (page: number) => {
  formSearch.current = page;
  queryData();
};

const optionsList = () => {
  getDictByParentCode({
    dictCode: "参赛项目来源",
  })
    .then((res) => {
      if (res.code === 200) {
        options["参赛项目来源"] = res.data[0].children;
        // itemText
        const find = options["参赛项目来源"].find(
          (item) => item.itemText === getUser().username
        );
        if (find) {
          formSearch.projectSource = find.id;
          options["参赛项目来源"] = [find];
        } else {
          formSearch.projectSource = "";
        }
      }
    })
    .finally(() => {
      listRacetrack()
        .then((res) => {
          if (res.code === 200) {
            options["企业赛道"] = res.data;
          }
        })
        .finally(() => {
          listNormalRacetrack()
            .then((res) => {
              if (res.code === 200) {
                options["赛道"] = res.data;
              }
            })
            .finally(() => {
              queryData();
            });
        });
    });
};

onMounted(() => {
  optionsList();
});

const columns = [
  {
    title: "序号",
    dataIndex: "index",
    width: 80,
    slotName: "index",
  },
  {
    title: "报名用户手机号",
    dataIndex: "phone",
    width: 135,
  },
  {
    title: "项目名称",
    dataIndex: "projectName",
    width: 135,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "参赛项目来源",
    dataIndex: "projectSource",
    width: 100,
  },
  {
    title: "赛题类型",
    dataIndex: "projectType",
    width: 90,
    slotName: "projectType",
  },
  {
    title: "赛道/赛题",
    dataIndex: "channel",
    width: 200,
    slotName: "channel",
  },
  {
    title: "参赛项目基本信息",
    dataIndex: "basicInfoIsOver",
    slotName: "basicInfoIsOver",
    width: 120,
  },
  {
    title: "参赛单位基本信息",
    dataIndex: "orgInfoIsOver",
    slotName: "orgInfoIsOver",
    width: 120,
  },
  {
    title: "团队信息",
    dataIndex: "teamInfoIsOver",
    slotName: "teamInfoIsOver",
    width: 180,
  },
  {
    title: "项目申报书",
    dataIndex: "projectApplicationIsOver",
    slotName: "projectApplicationIsOver",
    width: 95,
  },
  {
    title: "附件",
    dataIndex: "attachmentUploadIsOver",
    slotName: "attachmentUploadIsOver",
    width: 80,
  },
  {
    title: "状态",
    dataIndex: "status",
    slotName: "status",
    width: 80,
  },
  {
    title: "赛程",
    dataIndex: "stepStatus",
    slotName: "stepStatus",
    width: 80,
  },
  {
    title: "操作",
    dataIndex: "action",
    slotName: "action",
    width: 200,
  },
];

const handleSearch = () => {
  formSearch.current = 1;
  queryData();
};

const handleReset = () => {
  formSearch.current = 1;
  formSearch.size = 10;
  formSearch.phone = "";
  formSearch.projectType = "0";
  formSearch.projectSource = "";
  formSearch.channel = "";
  formSearch.dataDirection = "";
  formSearch.projectName = "";
  racetrackList.value = [];
  queryData();
};

const handleSelectChange = () => {
  formSearch.channel = "";
};

const handleChangeChannel = (e) => {
  formSearch.dataDirection = "";
  racetrackList.value = [];
  if (formSearch.projectType === "0") {
    const find = options["赛道"].find((item) => item.id === e);
    getDictByParentCode({
      dictCode: find.dictCode,
    }).then((res) => {
      if (res.code === 200) {
        racetrackList.value = res.data[0].children;
      }
    });
  } else if (formSearch.projectType === "1") {
    const find = options["企业赛道"].find((item) => item.id === e);
    getDictByParentCode({
      dictCode: find.dictCode,
    }).then((res) => {
      if (res.code === 200) {
        racetrackList.value = res.data[0].children;
      }
    });
  }
};

const handleInfoClick = (type, record) => {
  registUid.value = record.registUid;
  nextTick(() => {
    switch (type) {
      case "basicInfo":
        break;
      case "orgInfo":
        orginform.value?.show();
        break;
      case "teamInfo":
        break;
      case "projectApplication":
        helpform.value?.show();
        break;
      case "attachment":
        break;
      default:
        return;
    }
  });
};

const handleTableCancel = (row: any) => {
  ModalShow({
    content: "请确认是否退回当前报名信息。",
  }).then(() => {
    back({
      id: row.registUid,
    })
      .then((res) => {
        if (res.code === 200) {
          Message.success("报名信息已退回");
        }
      })
      .finally(() => {
        ModalHide();
        queryData();
      });
  });
};

const handleTableDownload = (row: any) => {
  downPdf(row.registUid).then((res) => {
    downloadFile(
      res,
      `${row.projectSource}-${row.projectType}-${row.channel}-${row.phone}-数据要素X河北分赛报名数据.zip`
    );
  });
};

const handleResetStep = (row: any) => {
  ModalShow({
    content: "请确认是否撤销当前淘汰报名信息。",
  }).then(() => {
    resetStep({
      id: row.registUid,
      step: "2",
    })
      .then((res) => {
        if (res.code === 200) {
          Message.success("淘汰信息已撤销");
        }
      })
      .finally(() => {
        ModalHide();
        queryData();
      });
  });
};

const handleINfoTable = (row) => {
  if (row.projectType === "常规赛题") {
    row.projectType = "0";
  }
  if (row.projectType === "企业需求子赛题") {
    row.projectType = "1";
  }

  achieveRef.value?.init({
    registUid: row.registUid,
    projectType: row.projectType,
  });
};
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form auto-label-width>
        <a-row :gutter="24">
          <a-col v-bind="colProps">
            <a-form-item label="项目名称">
              <a-input
                v-model="formSearch.projectName"
                placeholder="请输入项目名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="手机号">
              <a-input
                v-model="formSearch.phone"
                placeholder="请输入手机号"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="参赛项目来源">
              <a-select
                v-model="formSearch.projectSource"
                placeholder="请选择参赛项目来源"
              >
                <a-option
                  v-for="item in options['参赛项目来源']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.itemText }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="赛题类型">
              <a-select
                v-model="formSearch.projectType"
                @change="handleSelectChange"
                placeholder="请选择赛题类型"
              >
                <a-option value="0">常规赛题</a-option>
                <a-option value="1">企业需求子赛题</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="赛道">
              <a-select
                v-model="formSearch.channel"
                v-if="formSearch.projectType === '0'"
                placeholder="请选择赛道"
                @change="handleChangeChannel"
              >
                <a-option
                  v-for="item in options['赛道']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.dictName }}</a-option>
              </a-select>
              <a-select
                v-model="formSearch.channel"
                v-if="formSearch.projectType === '1'"
                placeholder="请选择赛道"
                @change="handleChangeChannel"
              >
                <a-option
                  v-for="item in options['企业赛道']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.dictName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="赛题">
              <a-select
                v-model="formSearch.dataDirection"
                placeholder="请选择赛题"
              >
                <a-option
                  v-for="item in racetrackList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.itemText }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-space>
              <a-button
                type="primary"
                @click="handleSearch"
              >
                <template #icon>
                  <icon-search />
                </template>
                <span>查询</span>
              </a-button>
              <a-button @click="handleReset">
                <template #icon>
                  <icon-refresh />
                </template>
                <span>重置</span>
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-table
        :data="data"
        :columns="columns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
        column-resizable="false"
        :loading="options.loading"
      >
        <template #index="{rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>
        <template #projectType="{record}">
          <a-tag
            v-if="record.projectType == '常规赛题'"
            bordered
            color="green"
          >常规</a-tag>
          <a-tag
            v-else-if="record.projectType == '企业需求子赛题'"
            color="orangered"
            bordered
          >企业</a-tag>
        </template>
        <template #channel="{record}">
          <div style="display: flex;flex-direction: column;">
            <span style="color: green;">{{ record.channel }}</span>
            <span style="color: orangered;">{{ record.dataDirection }}</span>
          </div>
        </template>
        <template #basicInfoIsOver="{record}">
          <a-tag
            v-if="record.basicInfoIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>
        <template #orgInfoIsOver="{record}">
          <!--          <a-link
              :style="{ textDecoration: 'underline' }"
              @click="handleInfoClick('orgInfo', record)"
              :status="record.orgInfoIsOver ? 'success' : 'danger'"
          >
            {{ record.orgInfoIsOver ? '已完成' : '未完成' }}
          </a-link>-->
          <a-tag
            v-if="record.orgInfoIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>
        <template #teamInfoIsOver="{record}">
          <a-tag
            v-if="record.teamInfoIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>
        <template #projectApplicationIsOver="{record}">
          <!--          <a-link
              :style="{ textDecoration: 'underline' }"
              @click="handleInfoClick('projectApplication', record)"
              :status="record.projectApplicationIsOver ? 'success' : 'danger'"
          >
            {{ record.projectApplicationIsOver ? '已完成' : '未完成' }}
          </a-link>-->
          <a-tag
            v-if="record.projectApplicationIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>
        <template #attachmentUploadIsOver="{record}">
          <a-tag
            v-if="record.attachmentUploadIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>
        <template #status="{record}">
          <a-tag
            bordered
            color="green"
            v-if="record.status === 1"
          >已提交</a-tag>
          <a-tag
            bordered
            color="orangered"
            v-else-if="record.status === 0"
          >未提交</a-tag>
        </template>
        <template #stepStatus="{record}">
          <a-tag
            bordered
            color="arcoblue"
            v-if="record.stepStatus === 2"
          >初赛</a-tag>
          <a-tag
            bordered
            color="magenta"
            v-else-if="record.stepStatus === 3"
          >决赛</a-tag>
          <a-tag
            bordered
            color="gray"
            v-else-if="record.stepStatus === 4"
          >淘汰</a-tag>
        </template>
        <template #action="{record}">
          <a-space type="primary">
            <a-button
              type="primary"
              @click="handleINfoTable(record)"
            >详细</a-button>
            <a-button
              v-has="'registrationCenter:weedout:steps'"
              @click="handleResetStep(record)"
              status="warning"
              type="outline"
            >撤销淘汰</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </a-space>
  <registration-form
    ref="helpform"
    @list="queryData"
    :registUid="registUid"
  />

  <registration-orgin
    ref="orginform"
    @list="queryData"
    :registUid="registUid"
  />

  <AchieveModal ref="achieveRef"></AchieveModal>
</template>

<style scoped lang="scss">
</style>